<template>
    <div>
        <Category :scene="scene"></Category>
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin-top:20px">
            <!-- 平台属性展示 -->
            <div v-show="scene==0">
                <el-button type="primary" size="default" :icon="Plus" style="margin-bottom:10px" @click="addAttr">添加属性
                </el-button>
                <el-table border stripe :data="attrList">
                    <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
                    <el-table-column label="属性名称" width="120" prop="attrName"></el-table-column>
                    <el-table-column label="属性值列表">
                        <template #="{row,$index}">
                            <el-tag class='ml-2' style="margin:0px 3px" :type="attrVal.id%2==0 ?'success':'warning'"
                                v-for="(attrVal,index) in row.attrValueList">{{attrVal.valueName}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #="{row,$index}">
                            <el-button type="primary" size="small" :icon="Edit" @click="updateAttr(row)"></el-button>
                            <el-button type="danger" size="small" :icon="Delete" @click="removeAttr(row)"></el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </div>
            <!-- 添加属性表格 -->
            <div v-show="scene==1">
                <el-form :inline="true" ref="form">
                    <el-form-item label="属性名">
                        <el-input placeholder="请你输入属性的名字" v-model="attrParams.attrName" clearable></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" :icon="Plus" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性值
                </el-button>
                <el-button @click="cancel"> 取消</el-button>
                <el-table border stripe style="margin:20px 0px" :data="attrParams.attrValueList">
                    <el-table-column label="序号" type="index" width="100"></el-table-column>
                    <el-table-column label="属性值">
                        <template #="{ row, $index }">
                            <el-input :ref="(vc) => (inputArr[$index] = vc)" v-if="row.flag" placeholder="请你输入属性值"
                                size="small" v-model="row.valueName" @blur="toLook(row, $index)"></el-input>
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{row,$index}">
                            <el-button type="danger" :icon="Delete" @click="attrParams.attrValueList.splice($index,1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="save" :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
                <el-button @click="cancel"> 取消</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, nextTick } from 'vue'
//引入图标
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
//引入仓库
import useCategoryStore from '@/stores/category';
//引入请求函数
import { reqAttrList, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr/attr';
let categoryStore = useCategoryStore();
//引入消息提示框
import { ElMessage } from "element-plus";
import _ from 'lodash'


//存储数据
let attrList = ref([]);
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref([]);
//场景值
let scene = ref<number>(0)

//添加/修改属性需要的参数
let attrParams = reactive({
    attrName: "", //新增|修改以后属性名字
    categoryId: "", //代表平台属性归属于手机这个三级分类下的
    categoryLevel: 3, //代表几级分类
    attrValueList: [],
});

//获取到三级分类的ID后发送请求
watch(
    () => categoryStore.c3Id,
    () => {
        //判断:三级分类ID保证有数据
        if (categoryStore.c3Id == "") return;
        //获取平台属性方法
        getAttrList();
    }
);
//获取商品属性的方法
const getAttrList = async () => {
    let result = await reqAttrList(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id);
    //存储数据
    attrList.value = result;
};

//添加属性的回调
const addAttr = () => {
    scene.value = 1;
    Object.assign(attrParams, {
        attrName: "",
        categoryId: categoryStore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
        categoryLevel: 3,
        attrValueList: [],
    });
}
//取消按钮切换场景
const cancel = () => {
    scene.value = 0
}

//添加属性值按钮的回调
const addAttrValue = () => {
    //向属性值数组添加元素
    attrParams.attrValueList.push({
        valueName: "",
        //给每一个属性值添加标记:用来切换编辑模式与查看模式
        flag: true,
    });
    //获取el-input组件实例,数组最后这个元素
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus();
    })
};

//input失却焦点变为查看模式
const toLook = (row, $index) => {
    //判断是否为空
    if (row.valueName.trim() == '') {
        ElMessage({
            type: 'warning',
            message: '属性值不能为空'
        });
        //去除当前属性值
        attrParams.attrValueList.splice($index, 1);
        return;
    }
    //属性值重复判断
    let repeat = attrParams.attrValueList.find((item) => {
        //判断前先去除自身
        if (row != item) {
            return row.valueName === item.valueName
        }
    })
    if (repeat) {
        ElMessage({
            type: 'warning',
            message: `${repeat.valueName}重复`
        })
        //去除当前属性值
        attrParams.attrValueList.splice($index, 1);
        return;
    }
    row.flag = false;
};
//div点击切换为编辑模式
const toEdit = (row,$index) => {
    row.flag = true;
    nextTick(() => {
        inputArr.value[$index].focus();
    });
};

const save = async () => {
    //参数整理一下:属性值的数组flag属性不需要--->干掉
    attrParams.attrValueList.forEach((item) => {
        if (item.hasOwnProperty("flag")) {
            //删除某一个属性
            delete item.flag;
        }
    });
    try {
        //添加属性成功
        await reqAddOrUpdateAttr(attrParams);
        //切换场景
        scene.value = 0;
        //提示
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改成功" : "添加成功",
        });
        //获取全部最新的属性的数据
        getAttrList();
    } catch (error) {
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改失败" : "添加失败",
        });
    }
};

//删除属性
const removeAttr = async(row)=>{
    try{
        await reqDeleteAttr(row.id)
        ElMessage({
            type: "success",
            message: `删除${row.attrName}成功`,
        })
        //获取最新的属性列表
        getAttrList();
    }catch(error){
        ElMessage({
            type: "error",
            message: `删除${row.attrName}失败`,
        })
    }
}

//编辑属性
const updateAttr = (row) => {
  scene.value = 1;
  Object.assign(attrParams, _.cloneDeep(row));
};

</script>

<style scoped>

</style>